var v_procedureContent = v_procedureContent;
var paramsDetail;
Ext.onReady(function() {

    Ext.create('Ext.Viewport', {
        layout:'fit',
        items:[{
            id:'main_panel',
            layout:'border',
            items:[getContentPanel() , getMsgPanel()]
        }]
    });
    initAll();
    setTableOptionsObject();
});

function getTableColumnUrl() {
	return getRoot() + '/websql/autoCompleteTableColumns?dataId='+dataBase_id+'&baseType='+base_type+'&dataSourceId='+dataSource_id+'&dataSource='+data_source+'&isLocal='+isLocal;
}

function getParamType() {
    return "column_group";
}

function setTableOptionsObject(comboValue) {
    var tmpNowDBName = comboValue ? comboValue : nowDBName;
    ajax({//发送同步请求
        async:false,
        url:getTableColumnUrl(),
        params:{dbName:tmpNowDBName},
        success:function(resp) {
            var json = jsonDecode(resp.responseText);
            if (json.success) {
                var databaseData = json.databases;
                CM_NOW_DATABASE = tmpNowDBName;
                var tableData = json.tables;
                var databaseResObj = {};
                var tableResObj = {};
                for (var i = 0; i < databaseData.length; i ++) {
                    databaseResObj[databaseData[i].databaseName] = null;
                }
                for (var i = 0; i < tableData.length; i ++) {
                    var tmpName = tableData[i].tableName;
                    var tmpComment = tableData[i].tableComment;
                    tableResObj[tmpName] = {"__cm__comment":tmpComment};
                }
                CM_TABLES = tableResObj;
                databaseResObj[CM_NOW_DATABASE] = CM_TABLES;
                CM_DATABASES = databaseResObj;
                Ext.getCmp('sql_content').editor.setOption('hintOptions', {databases:databaseResObj, tables:tableResObj});
            }
        }
    });
};

var initAll = function() {
    if(v_procedureName) {
        initHeaderPanel();
        setContent(v_procedureContent);
        if(v_init_option == 'execute') {
            action_fun.executeProcedure();
        }
    }else {
    	createNewProcedureInfo();
    }
};
var toRows = 4;
var getCreateProcedureSQL = function() {
    var content = "CREATE PROCEDURE " + nowDBName.replaceAll('`' ,'') + "." + '<NAME>' + "()\n";
    content += "\tNOT DETERMINISTIC\n";
    var comment = '<COMMENT>';
    if(comment && comment.trim()) {
        comment = comment.trim();
        toRows += comment.length - comment.replaceAll("\n" , "").length + 1;
        content += '\tCOMMENT \'' + comment.replaceAll("'" , "''") + "'\n";
    }
    content += '\nBEGIN\n\t\n';
    content += 'END\n';
    return content;
};

var createNewProcedureInfo = function(){
	initHeaderPanel();
    var sqlContent = Ext.getCmp('sql_content');
    sqlContent.setValue(getCreateProcedureSQL());
    sqlContent.editor.focus(true);
    sqlContent.editor.setCursor(toRows , 2);
}

var showNewProcedureBaseInfo = function(force,fn) {
	var projectStore = new Ext.data.Store({
		fields:['data','label'],
		data : projectListArray
	});
    var baseInfoForm = new IDB.FormPanel({
        region:'center',
        layout:'column',
        defaults:{margin: '5 2 6 0',width:500,columnWidth:1,labelWidth:90,allowBlank:false},
        items:[{
            fieldLabel:'存储过程名称',
            blankText:'存储过程不能为空',
            xtype:'textfield',
            name:'name',
            maxLength:128,
            maxLengthText:'存储过程名称请小于128个字符'
        },{
        	fieldLabel:'<span style="color:red">*</span>邮箱',
     	   	emptyText:'请输入部门负责人邮箱地址',
     	   	allowBlank:false,
     	   	name:'auserEmail',
     	   	blankText:'部门负责人邮箱地址不能为空'
        },{
        	fieldLabel:'项目组',
        	xtype:'combo',
        	triggerAction:'all',
        	displayField:'label',
        	valueField:'data',
        	queryMode:'local',
        	name:'projectName',
        	forceSelection:true,
        	typeAhead:true,
        	editable:false,
        	store:projectStore
        },{
        	padding:'5 0 0 0',
        	fieldLabel:'<span style="color:red">*</span> SQL用途',
        	allowBlank:false,
        	name:'sqlUsage',
        	blankText:'SQL用途说明不能为空.'
        },{
            fieldLabel:'描述',
            xtype:'textarea',
            height:40,
            maxLength:1024,
            maxLengthText:'描述的内容请不要超过1024个字符',
            name:'comment',
            allowBlank:true
        }]
    });

    var toRows;
    var win = new IDB.Window({
        width:520,height:260,title:'请填写存储过程的基本信息',layout:'fit',closable:false,buttonAlign:'center',
        items:[baseInfoForm],
        buttons:[{
            text:'确 定',
            handler:function(){
                if(baseInfoForm.isValid()) {
                	paramsDetail = baseInfoForm.getValues();
                	action_fun.cleanMsg();
                    Ext.getCmp('msg_panel').show();
                    var content = Ext.getCmp('sql_content').getValue();
                    if(!content || content.trim().length == 0) {
                        return Ext.Msg.alert('提示', '存储过程的内容不能为空。');
                    }
                    paramsDetail.script = content;
                    paramsDetail.dbName = nowDBName;
                    paramsDetail.oldProcedureName = v_procedureName;
                    paramsDetail.forceExecute = force;
                    paramsDetail.databaseId = dataBase_id;
                    paramsDetail.datasourceId = dataSource_id;
                    paramsDetail.dataSource = data_source;
                    paramsDetail.baseType = now_db_type;
                    paramsDetail.isLocal = isLocal;
                    paramsDetail.sqlType = 'A SQL';
                    Ext.getBody().mask('正在保存存储过程，请等待...');
                    ajax({
                        url:getRoot()+'/dataManage/executeScript',
                        params:paramsDetail,
                        success:function(resp) {
                            Ext.getBody().unmask();
                            Ext.getCmp('msg_panel').show();
                            var json = jsonDecode(resp.responseText);
                            var data = json.root;
                            if(json.success) {
                            	if(isLocal =='isLocal'){
                            		$.message.success(""+data);
                            	}else{
                            		$.feedbackMessage({type: 'success',message: data,showTime:5000});
                            	}
                            }else {
                                action_fun.saveErrorProcess(data);
                            }
                        }
                    });
                    win.close();
                }
            }
        },{
            text:'关 闭',
            handler:function() {
                win.close();
            }
        }],
        listeners:{
            'afterrender' : function() {
                setTimeout(function() {
                    baseInfoForm.getForm().findField('name').focus(true);
                } , 200);
            }
        }
    });
};

var setContent = function(v) {
    var sqlContent = Ext.getCmp('sql_content');
    sqlContent.setValue(v);
    sqlContent.editor.focus(true);
    var index = v.toUpperCase().indexOf("BEGIN");
    var tmp = v.substring(0 , index);
    var rows = tmp.length - tmp.replaceAll("\n" , "").length;
    var rowContent = sqlContent.editor.getLine(rows + 1);
    sqlContent.editor.setCursor(rows + 1 , rowContent.length);
};

var initHeaderPanel = function() {
    Ext.getCmp('main_panel').add(getHeaderPanel());
    document.getElementById('header_panel_div').style.backgroundColor = "#f5f5f5";
    var tyeStr = "";
    if(envType != 'PRD'){
    	tyeStr += '<input type="button" value="创建" onclick="action_fun.executeProcedure();" class="button_class_1" style="width: 80px;height: 32px;margin: 10px 0 0 10px;"/>';
    }else{
    	tyeStr += '<input type="button" value="保存" onclick="action_fun.saveProcedure(\'false\');" class="button_class_1" style="width: 80px;height: 32px;margin: 10px 0 0 10px;"/>';
    }
    document.getElementById('header_panel_div').innerHTML =
        tyeStr+
        '<span style="width: 80px;height: 32px;margin: 10px 0 0 10px;"/>当前库：<span id="db_name_div">' + nowDBName + "</span></span>" +
        '<input type="button" value="帮助" onclick="action_fun.linkHelp();" class="button_class_2" style="width: 90px;height: 32px;float: right;margin: 10px 30px 0 0;"/>' ;
        //+'<input type="button" value="选项设置" onclick="action_fun.setInfoBefore();" class="button_class_3" style="width: 100px;height: 32px;float: right;margin: 10px 30px 0 0;"/>';
};

var getHeaderPanel = function() {
    return new Ext.Panel({
        id:'header_panel_panel',
        region:'north',height:55,
        bodyStyle: 'border-style:solid;border-width:1px;border-color:#eee;',
        border:true,
        html:'<div id="header_panel_div" style="height: 100%">&nbsp;</div>'
    });
};
var resetNowDBName = function() {
    document.getElementById('db_name_div').innerHTML = nowDBName;
};

var getContentPanel = function() {
    var sqlArea = new Ext.ux.form.field.CodeMirror({value: '',id:'sql_content', autoScroll: true , styleActiveLine: true});
    return new Ext.Panel({
        id:'content_area',
        layout:'fit',region:'center',
        bodyStyle: 'border-style:solid;border-width:1px;border-color:#eee;',
        border:true,
        items:[sqlArea]
    });
};

var getMsgPanel = function() {
    return new Ext.tab.Panel({
        id:'msg_panel',
        margin:"5 0 0 5",
        activeTab: 0,
        region:'south' ,
        minTabWidth: 70,
        maxTabWidth: 160,
        height:220,
        hidden:true,
        split:true,
        collapsible: false,
        items:[{
            title:'消息',
            autoScroll:true,
            xtype:'container',
            id:'ext_msg_panel_area',
            html:'...'
        }]
    });
};
var resetDisplayColumns = function(result) {
    for (var rec in result.data) {
        for (var key in result.data[rec]) {
            var value = result.data[rec][key];
            if ((key.substr(0, 7) == "COLUMN_") && (typeof value == 'string')) {
                var newWidth = value.byteLength() * 10;
                var colIndex = key.substr(7, 3);
                if (newWidth > 400) {
                    newWidth = 400;
                }
                if ((newWidth > result.displayColumns[colIndex].width)) {
                    result.displayColumns[colIndex].width = newWidth;
                }
            }
        }
    }
};
function rendererResultValue(value, meta, record, rowIndex, colIndex,store,view , result_index) {
    var columnName = 'COLUMN_' + colIndex;
    var grid = Ext.getCmp('result_' + result_index);
    var metaData = grid.metadata[colIndex - 1];
    var v_primaryKeys = grid.editTablePrimaryKeys;
    var metaDataType = metaData['dataType'];

    if (!isNull(value) && (record.raw.hasOwnProperty(columnName) || record.data[columnName] !== '')) {
        if(v_primaryKeys && v_primaryKeys.length > 0 && metaDataType.indexOf('BLOB') != -1 && !isNewRecord(grid, record)) {
            return value + "<br/><a href='javascript:row_fun.downloadBlob("+ result_index + "," + colIndex  +")'>下载</a>" +
                " <a href='javascript:row_fun.uploadBlob("+ result_index + "," + colIndex + ")'>上传</a>";
        }
        return encodeValue(value, meta, record);
    } else {
        if(v_primaryKeys && v_primaryKeys.length > 0 && metaDataType.indexOf('BLOB') != -1 && !isNewRecord(grid, record)) {
            return '<i style=\"color:#E5E5E5;\">null</i>' + "<br/>" +
                " <a href='javascript:row_fun.uploadBlob("+ result_index + "," + colIndex + ")'>上传</a>";
        }
        // NULL值背景显示白灰色
        return '<i style=\"color:#E5E5E5;\">null</i>';
    }
}
function moveRowResult(option,grid) {
    var selectionModel = grid.getSelectionModel();
    if (option == 'first') {
        selectionModel.select(0);
    } else if (option == 'last') {
        selectionModel.select(grid.store.getCount() - 1);
    } else if (option == 'previous') {
        selectionModel.select(grid.store.indexOf(selectionModel.lastSelected) - 1);
    } else if (option == 'next') {
        selectionModel.select(grid.store.indexOf(selectionModel.lastSelected) + 1);
    }
}
function encodeValue(value, meta, record) {
    return '<pre style="padding: 0;margin:0;font-family:新宋体,Lucida Console,monospace">' + Ext.util.Format.htmlEncode(value) + '</pre>';
}
function isNull(value) {
    return (value == null);
}
var action_fun = {
    now_parameters:{},
    linkHelp:function() {
        window.open('https://dev.mysql.com/doc/refman/5.6/en/create-procedure.html');
    },
    cleanMsg:function() {
        action_fun.getMsgDom().innerHTML = "&nbsp;";
    },
    showExecuteMsg:function(msg) {
        action_fun.cleanMsg();
        Ext.getCmp('msg_panel').show();
        action_fun.getMsgDom().innerHTML = msg;
    },
    appendExecuteMsg:function(msg) {
        Ext.getCmp('msg_panel').show();
        var innerHTML = action_fun.getMsgDom().innerHTML;
        action_fun.getMsgDom().innerHTML = innerHTML + msg;
    },
    saveErrorProcess:function(msg) {
        Ext.getCmp('msg_panel').show();
        var errorLineIndex = -1, lineIndex = -1;
        if(msg.contains("at line")) {
            lineIndex = msg.indexOf("at line");
            if(lineIndex != -1) {
                errorLineIndex = parseInt(msg.substring(lineIndex + 7).trim()) - 1;
            }
        }
        if(msg.contains("You have an error in your SQL syntax") && msg.contains("syntax to use near")) {
            var index = msg.indexOf("near");
            msg = "在以下代码附近存在语法错误：\n" + msg.substring(index + 4).trim();
        }
        action_fun.getMsgDom().innerHTML = "<span style='font-size: 16px;color: red'>存储过程保存失败：</span><br/>" + msg;
        if(errorLineIndex != -1) {
            var sqlContent = Ext.getCmp('sql_content');
            var lineContent = sqlContent.editor.getLine(errorLineIndex);
            sqlContent.editor.focus(true);
            sqlContent.editor.setCursor(errorLineIndex , lineContent.length);
            var codeMirrors = Ext.select('.CodeMirror-linebackground');
            codeMirrors.each(function(ele) {
                console.log(ele.getStyle('background-color'));
                ele.setStyle('background-color' , "red");
                ele.setStyle('opacity' , '0.45');
            });
        }
    },
    executeProcedureSetParams:function(params , procedureName , dbName) {
        var inputParams = [], outParams = [], outParamsStr = "";
        params.each(function(row) {
            var use = row['parameterUse'];
            if(use == 'IN' || use == 'INOUT') {
                var name = row['name'];
                if(action_fun.now_parameters[name]) {
                    row['value'] = action_fun.now_parameters[name];
                }
                inputParams.push(row);
                if(use == 'INOUT') {
                    outParams.push(row);
                    outParamsStr += row['name'] + " " + row['type'] + "，";
                }
            }else {
                outParams.push(row);
                outParamsStr += row['name'] + " " + row['type'] + "，";
            }
        });
        var paramStore = new Ext.data.Store({
            fields:['name' , 'type' , 'value' , "parameterUse"],
            data:inputParams,
            proxy: {
                type: 'memory'
            }
        });

        var grid = new Ext.grid.Panel({
            selType: 'rowmodel',
            region: 'center',
            viewConfig:{ stripeRows:true, enableTextSelection:true},
            plugins: [
                new Ext.grid.plugin.CellEditing({
                    clicksToEdit: 1
                })
            ],
            columns:[
                {xtype: 'rownumberer'},
                { text: '参数',  dataIndex: 'name' ,width:275 ,sortable:false , renderer:function(v,css,row) {
                    return "<span style='font-weight: bold'>" + row.get('parameterUse') + "<span style='padding-left: 10px'>" + v + "</span></span><span style='padding-left: 10px;'> " + row.get('type') + "</span>";
                }},
                { text: '参数值',  dataIndex: 'value' ,width:400 ,sortable:false , editor:{xtype:'textfield'}}
            ],
            store:paramStore
        });
        var msg = "[OUT参数说明]：该存储过程没有任何OUT参数";
        if(outParamsStr.length > 0) {
            outParamsStr = outParamsStr.substring(0 , outParamsStr.length - 1);
            msg = "<span style='font-weight: bold'>[OUT参数包含]：</span>" + outParamsStr + "<br/>存储过程成功执行完成，其结果将显示在消息中。";
        }
        var msgPanel = new Ext.Panel({
            title:'OUT参数提示',
            region:'south',height:85,
            html:'<div style="padding-left: 20px;padding-top: 10px;">' + msg + '</div>'
        });
        var win = new IDB.Window({
            width: 720, height: 360, title: '请设置存储过程的入口参数值', layout: 'border', buttonAlign: 'center', closable: true,
            items: [grid , msgPanel],
            buttons:[{
                text:'开始执行',handler:function() {
                    action_fun.now_parameters = {};
                    grid.store.each(function(row) {
                        var v = row.get('value');
                        if(v && Ext.util.Format.trim(v).length > 0) {
                            action_fun.now_parameters[row.get('name')] = v;
                        }
                    });
                    params.each(function(row) {
                        var name = row['name'];
                        if(action_fun.now_parameters[name]) {
                            row['value'] = action_fun.now_parameters[name]
                        }
                    });
                    action_fun.executeProcedureDoing(params , procedureName , dbName);
                    win.close();
                }
            },{
                text:'取消',handler:function() {win.close()}
            }]
        });
    },
    executeProcedure : function() {
        var content = Ext.getCmp('sql_content').getValue();
        if(!content || content.trim().length == 0) {
            Ext.Msg.alert('提示' , '存储过程的内容不能为空。');
        }
        if(envType != 'PRD'){
        	Ext.getBody().mask('正在获取存储过程的参数信息...');
            ajax({
                url:getRoot()+'/dataManage/executeScript',
                params:{script:content,dbName:nowDBName,databaseId:dataBase_id,datasourceId:dataSource_id,dataSource:data_source,baseType:now_db_type,isLocal:isLocal,objectType:'PROCEDURE'},
                success:function(resp) {
                    Ext.getBody().unmask();
                    var json = jsonDecode(resp.responseText);
                    var data = json.root;
                    if(json.success) {
                    	Ext.getCmp('msg_panel').hide();
                    	if(isLocal =='isLocal'){
                    		$.message.success(""+data);
                    	}else{
                    		$.feedbackMessage({type: 'success',message: data,showTime:5000});
                    	}
                    }else {
                        action_fun.saveErrorProcess(data);
                    }
                }
            });
        }else{
        	action_fun.saveProcedure(true , action_fun.executeProcedure);
//        	if(!v_procedureContent || v_procedureContent != content) {
//                action_fun.saveProcedure(true , action_fun.executeProcedure);
//            }else {
//                Ext.getBody().mask('正在获取存储过程的参数信息...');
//                ajax({
//                    url:getRoot()+'/dataManage/executeScript',
//                    params:{script:content,dbName:nowDBName,databaseId:dataBase_id,datasourceId:dataSource_id,dataSource:data_source,baseType:now_db_type,isLocal:isLocal},
//                    success:function(resp) {
//                        Ext.getBody().unmask();
//                        var data = jsonDecode(resp.responseText);
//                        if(data.success) {
//                            var params = data.root['params'];
//                            if(params && params.length > 0) {
//                                action_fun.executeProcedureSetParams(params , data.root['name'] , data.root['dbName']);
//                            }else {
//                                action_fun.executeProcedureDoing([] , data.root['name'] , data.root['dbName']);
//                            }
//                        }else {
//                            $.message.error("存储过程参数信息获取失败：" + data.root);
//                        }
//                    }
//                });
//            }
        }
    },
    getExecuteMsgWindow:function() {
        return new Ext.Window({
            width:550,
            height:180,
            layout:'absolute',
            title:'存储过程正在执行中',
            overflowY : 'scroll',
            plain:true,
            bodyStyle:'padding:5px;',
            buttonAlign:'center',
            items:[
                {
                    x:20,
                    y:20,
                    xtype:'label',
                    text:'存储过程还在执行中，请不要强制刷新或关闭页面......'
                }
            ],
            closable:false
        });
    },
    maskTop:function() {
        Ext.getCmp('content_area').mask('...');
        Ext.getCmp('header_panel_panel').mask('...');
    },
    unmaskTop:function() {
        Ext.getCmp('content_area').unmask();
        Ext.getCmp('header_panel_panel').unmask();
    },
    isExecute:false,
    executeProcedureDoing:function(parameters , procedureName , dbName) {
        if(action_fun.isExecute) {
            return;
        }
        action_fun.isExecute = true;
        var parameterStr = JSON.stringify(parameters);
        var lastData = "";
        action_fun.maskTop();
        var msgWindow = action_fun.getExecuteMsgWindow();
        msgWindow.show();
        action_fun.cleanMsg();
        action_fun.clearTabPanelResult();
        ajaxLongTime({
            url:'/structure/procedure/execute-procedure.do',
            getDataUrl:'/structure/procedure/get-procedure-result.do',
            maxRequestTimeout:10000,
            params:{parameters:parameterStr , name:procedureName , dbName:dbName},
            success:function(resp) {
                action_fun.isExecute = false;
                msgWindow.close();
                action_fun.unmaskTop();
                var json = jsonDecode(resp.responseText);
                if(json.success) {
                    var data = json.root;
                    var result = data.results;
                    var middleResultArrayKey = [], outputParameterResultKey;
                    var displayMsg = "<div style='padding-top: 6px;padding-left: 8px;'>存储过程执行成功，耗时：[ " + commons_tools.numberWithCommas(data.timeDelay) + "ms. ] </div>";
                    if(data.results && data.results.length > 0) {
                        var index = 0;
                        data.results.each(function(row) {
                            if(!row['tag']) {
                                index++;
                                middleResultArrayKey.push(row);
                            }else {
                                outputParameterResultKey = row;
                            }
                        });
                        if(index > 0) {
                            displayMsg = displayMsg + "<div style='padding-top: 6px;padding-left: 8px;'>获取到存储过程中间结果集数量：" + index + "，正在输出结果集信息....</div>";
                            if(index > 10) {
                                displayMsg = displayMsg + "<div style='padding-top: 6px;padding-left: 8px;'>结果集数量太多可能会导致浏览器崩溃，DMS默认展示前10个结果集。</div>";
                            }
                        }
                        if(outputParameterResultKey) {
                            displayMsg = displayMsg + "<div style='padding-top: 6px;padding-left: 8px;'>存储过程包含了OUT参数</div>";
                        }else {
                            displayMsg = displayMsg + "<div style='padding-top: 6px;padding-left: 8px;'>存储过程没有任何OUT参数，跳过获取OUT参数值</div>";
                        }
                    }
                    action_fun.showExecuteMsg(displayMsg);
                    if(outputParameterResultKey) {
                        action_fun.showProcedureOutputParams(outputParameterResultKey , middleResultArrayKey);
                    }else if(middleResultArrayKey.length > 0) {
                        action_fun.showProcedureResults(middleResultArrayKey , 0 , new Date().getTime());
                    }else {
                        action_fun.appendExecuteMsg("<div style='padding-top: 20px;padding-left: 8px;'>存储过程没有OUT参数返回值且没有结果集，消息结束.</div>")
                    }
                }else {
                    action_fun.showExecuteMsg("<div style='padding-top: 6px;color: red;padding-left: 8px;'>执行存储过程报错：" + json.root + "</div>");
                }
            },
            notifyTime:function(time) {
                msgWindow.items.get(0).setText('过程还在执行中，请不要强制刷新或关闭页面，大概已执行：[ ' + commons_tools.numberWithCommas(time) + "ms. ]" + lastData, false);
            },
            notifyData:function(resp , time) {
                var data = jsonDecode(resp.responseText).root;
                if(data.results && data.results.length > 0) {
                    var index = 0;
                    data.results.each(function(row) {
                        if(!row['tag']) {
                            index++;
                        }
                    });
                    lastData = "<div style='padding-top: 10px;'>已获取到【存储过程】运行中产生的结果集数量：" + index + "</div>";
                }
                action_fun.showExecuteMsg(lastData);
                msgWindow.items.get(0).setText('过程还在执行中，请不要强制刷新或关闭页面，大概已执行：[ ' + commons_tools.numberWithCommas(time) + "ms. ]" + lastData, false);

            }
        });
    },
    clearTabPanelResult:function() {
        var tabPanel = Ext.getCmp('msg_panel');
        var items = tabPanel.items;
        if(items.length > 1) {
            for(var i = items.length - 1 ; i > 0 ; i--) {
                tabPanel.remove(i,true);
            }
        }
    },
    showProcedureResults:function(array , index , showTimestamp) {
        if(index >= 10) {
            action_fun.appendExecuteMsg("<div style='padding-top: 12px;padding-left: 25px;'>结果集数量过多，可能会导致浏览器崩溃，DMS限制最多显示10个结果集，后续结果集已忽略..</div>");
            action_fun.scrollLast();
        }else {
            action_fun.appendExecuteMsg("<div style='padding-top: 12px;padding-left: 25px;'>获取获取第[ " + (index + 1) + " ]个中间结果集。</div>");
            ajax({
                url:'/structure/procedure/get-procedure-detail-result.do',
                params:{id:array[index]['id']},
                success:function(resp) {
                    var json = jsonDecode(resp.responseText);
                    if(json.success) {
                        action_fun.appendExecuteMsg("<div style='padding-top: 6px;padding-left: 25px;'>中间结果集获取成功...</div>");
                        var data = json.root;
                        Ext.getCmp('msg_panel').add(action_fun.createOneResult(data , index));
                    }else {
                        action_fun.appendExecuteMsg("<div style='padding-top: 6px;padding-left: 25px;'>获取中间结果集失败：" + json.root + "</div>");
                    }
                    action_fun.scrollLast();
                    if(index < array.length - 1) {
                        action_fun.showProcedureResults(array , index + 1 , showTimestamp);
                    }else {
                        action_fun.appendExecuteMsg("<div style='padding-top: 30px;padding-left: 25px;padding-bottom: 10px;'>所有中间结果集获取完成。</div>");
                        action_fun.scrollLast();
                    }
                }
            });
        }
    },
    createOneResult:function(result , index) {
        for (var i = 1; i < result.displayColumns.length; i++) {
            result.displayColumns[i].renderer = function(value, meta, record, rowIndex, colIndex,store,view) {
                return rendererResultValue(value, meta, record, rowIndex, colIndex,store,view , index);
            };
        }
        resetDisplayColumns(result);
        var fields = [];
        var store = new Ext.data.Store({
            fields:result.metadata,
            data:result.data,
            proxy: {
                type: 'memory'
            }
        });
        var grid = new Ext.grid.Panel({
            title:'中间结果集' + (index + 1),
            id:'result_' + index,
            sortableColumns:false,
            multiSelect:true,
            store:store,
            viewConfig:{ stripeRows:true, enableTextSelection:true},
            columns:result.displayColumns,
            listeners:{
                afterrender:function() {
                    //moveRowResult("first" , grid);
                }
            }
        });
        grid.dbName = nowDBName;
        grid.metadata = result.metadata;
        return grid;
    },
    showProcedureOutputParams:function(outputParameterResultKey , middleResultArrayKey) {
        action_fun.appendExecuteMsg("<div style='padding-top: 12px;padding-left: 25px;'>正在获取存储过程OUT参数及INOUT参数的值...</div>");
        ajax({
           url:'/structure/procedure/get-procedure-detail-result-kv.do',
            params:{id:outputParameterResultKey['id']},
            success:function(resp) {
                var json = jsonDecode(resp.responseText);
                if(json.success) {
                    var data = json.root;
                    if(data.length > 0) {
                        var rows = data[0];
                        for(var i = 0, size = rows.length ; i < size ; i++) {
                            var kv = rows[i];
                            var value = kv.value || "NULL";
                            action_fun.appendExecuteMsg("<div style='padding-top: 6px;padding-left: 25px;'><span style='font-weight: bold'> 返回参数 [" + (i + 1) + "]、</span>" + kv.key + " = " + value + "</div>");
                            action_fun.scrollLast();
                        }
                    }
                }else {
                    action_fun.appendExecuteMsg("<div style='padding-top: 6px'>获取存储过程返回值失败：" + json.root + "</div>");
                }
                action_fun.showProcedureResults(middleResultArrayKey , 0 , new Date().getTime());
            }
        });
    },
    scrollLast:function() {
        var nowLogContentDom = action_fun.getMsgDom();
        nowLogContentDom.scrollTop = nowLogContentDom.scrollHeight;
    },
    getMsgDom:function() {
        return Ext.getCmp('ext_msg_panel_area').el.dom;
    },
    refreshProcedureCallBack:function(name , type , dbName) {
        if(window.onunload) {
            window.onunload = null;
        }
        if(window.onbeforeunload) {
            window.onbeforeunload = null;
        }
        window.parent.refreshProcedureCallBack(tabId , name , type , dbName , panelKey);
    },
    saveProcedure:function(force , fn) {
    	showNewProcedureBaseInfo(force,fn);
    },
    setInfoBefore:function() {
        var content = Ext.getCmp('sql_content').getValue();
        Ext.getBody().mask('正在解析存储过程选项信息....');
        ajax({
            url:getRoot()+'/dataManage/getProcedureConfig',
            params:{script:content,dbName:nowDBName},
            success:function(resp) {
                Ext.getBody().unmask();
                var json = jsonDecode(resp.responseText);
                if(json.success) {
                    action_fun.setInfo(json.root);
                }else {
                    action_fun.saveErrorProcess(json.root);
                }
            }
        });
    },
    setInfo:function(config) {
        var baseInfoForm = new Ext.Panel({
            region: 'center',
            layout: {
                type: 'vbox',
                align:'left'//左边对其
            },
            defaults: {padding:'10 2 2 2'},
            items:[{
                //SQL_SECURITY
                height:55,
                layout: {
                    type: 'hbox',
                    align:'top'//向上对其
                },
                items:[
                    {
                        xtype:'panel',
                        width:130,
                        html:'<span style="margin-right: 13px;float: right;margin-top: 10px;font-weight: bold">' +
                        '<span style="font-size: 13px;">SQL_SECURITY：</span>' +
                        '</span>'
                    },{
                        xtype:'panel',
                        width:90,
                        html:'<span style="margin-right: 13px;">' +
                        '<input name="v_saveSecurityField" type="button" value="默认" onclick="action_fun.select(this)" class="radio_class_1" style="width: 80px;height: 29px;"/>' +
                        '</span>'
                    }, {
                        xtype:'panel',
                        width:90,
                        html:'<span style="margin-right: 13px;">' +
                        '<input name="v_saveSecurityField" type="button" value="INVOKER" onclick="action_fun.select(this)" class="radio_class_2" style="width: 80px;height: 29px;"/>' +
                        '</span>'
                    }, {
                        xtype:'panel',
                        width:90,
                        html:'<span style="margin-right: 13px;">' +
                        '<input name="v_saveSecurityField" type="button" value="DEFINER" onclick="action_fun.select(this)" class="radio_class_2" style="width: 80px;height: 29px;"/>' +
                        '</span>'
                    }
                ]
            },{
                //决定性
                height:55,
                layout: {
                    type: 'hbox',
                    align:'top'//向上对其
                },
                items:[
                    {
                        xtype:'panel',
                        width:130,
                        html:'<span style="margin-right: 13px;float: right;margin-top: 10px;font-weight: bold">' +
                        '<span style="font-size: 13px;">决定性：</span>' +
                        '</span>'
                    },{
                        xtype:'panel',
                        width:120,
                        html:'<span style="margin-right: 13px;">' +
                        '<input name="v_deterministicField" type="button" value="DETERMINISTIC" onclick="action_fun.select(this)" class="radio_class_2" style="width: 110px;height: 29px;"/>' +
                        '</span>'
                    },{
                        xtype:'panel',
                        width:140,
                        html:'<span style="margin-right: 13px;">' +
                        '<input name="v_deterministicField" type="button" value="NOT DETERMINISTIC" onclick="action_fun.select(this)" class="radio_class_1" style="width: 130px;height: 29px;"/>' +
                        '</span>'
                    }
                ]
            },{
                //数据访问
                height:55,
                layout: {
                    type: 'hbox',
                    align:'top'//向上对其
                },
                items:[
                    {
                        width:130,
                        xtype:'panel',
                        html:'<span style="margin-right: 13px;float: right;margin-top: 10px;">' +
                        '<span style="font-size: 13px;font-weight: bold">数据访问：</span>' +
                        '</span>'
                    },
                    {
                        xtype:'panel',
                        width:90,
                        html:'<span style="margin-right: 12px;">' +
                        '<input name="v_callMethodField" type="button" value="默认" onclick="action_fun.select(this)" class="radio_class_1" style="width: 80px;height: 29px;"/>' +
                        '</span>'
                    },
                    {
                        xtype:'panel',
                        width:115,
                        html:'<span style="margin-right: 12px;">' +
                        '<input name="v_callMethodField" type="button" value="CONTAINS SQL" onclick="action_fun.select(this)" class="radio_class_2" style="width: 105px;height: 29px;"/>' +
                        '</span>'
                    },
                    {
                        xtype:'panel',
                        width:80,
                        html:'<span style="margin-right: 12px;">' +
                        '<input name="v_callMethodField" type="button" value="NO SQL" onclick="action_fun.select(this)" class="radio_class_2" style="width: 70px;height: 29px;"/>' +
                        '</span>'
                    },
                    {
                        xtype:'panel',
                        width:130,
                        html:'<span style="margin-right: 12px;">' +
                        '<input name="v_callMethodField" type="button" value="READS SQL DATA" onclick="action_fun.select(this)" class="radio_class_2" style="width: 120px;height: 29px;"/>' +
                        '</span>'
                    },
                    {
                        xtype:'panel',
                        width:140,
                        html:'<span style="margin-right: 12px;">' +
                        '<input name="v_callMethodField" type="button" value="MODIFIES SQL DATA" onclick="action_fun.select(this)" class="radio_class_2" style="width: 130px;height: 29px;"/>' +
                        '</span>'
                    }
                ]
            }
            ]
        });

        var win = new IDB.Window({
            width:720,height:260,title:'存储过程的选项设置',layout:'fit',buttonAlign:'center',closable:true,
            items:[baseInfoForm],
            buttons:[{
                text:'确 定',handler:function() {
                    var data = {
                        sqlSecurity:action_fun.getValueByName("v_saveSecurityField"),
                        deterministic:action_fun.getValueByName("v_deterministicField"),
                        dataCallMethod:action_fun.getValueByName("v_callMethodField"),
                        script:Ext.getCmp('sql_content').getValue()
                    };
                    ajax({
                        url:getRoot()+'/dataManage/setProcedureConfig',
                        params:data,
                        success:function(resp) {
                            var json = jsonDecode(resp.responseText);
                            if(json.success) {
                                setContent(json.root);
                                win.close();
                            }else {
                                $.message.error(json.root);
                            }
                        }
                    });
                }
            },{
                text:'关 闭',
                handler:function() {
                    win.close();
                }
            },{
                text:'帮助',handler:function() {
                    action_fun.linkHelp();
                }
            }]
        });

        if(config['sqlSecurity']) {
            action_fun.selectByValue("v_saveSecurityField" , config['sqlSecurity']);
        }
        if(config['dataCallMethod']) {
            action_fun.selectByValue("v_callMethodField" , config['dataCallMethod']);
        }
        if(config['deterministic']) {
            action_fun.selectByValue("v_deterministicField" , config['deterministic']);
        }
    },
    select:function(obj) {
        var name = obj.name;
        var fields = document.getElementsByName(name);
        for(var i = 0, size = fields.length ; i < size ; i++) {
            if(fields[i] == obj) {
                fields[i].setAttribute("class" , "radio_class_1");
            }else {
                fields[i].setAttribute("class" , "radio_class_2");
            }
        }
    },
    selectByValue:function(name , value) {
        var fields = document.getElementsByName(name);
        for(var i = 0, size = fields.length ; i < size ; i++) {
            if(fields[i].value  == value.toUpperCase()) {
                fields[i].setAttribute("class" , "radio_class_1");
            }else {
                fields[i].setAttribute("class" , "radio_class_2");
            }
        }
    },
    getValueByName : function(name) {
        var fields = document.getElementsByName(name);
        var node = null;
        for(var i = 0, size = fields.length ; i < size ; i++) {
            if(fields[i].getAttribute("class") == "radio_class_1") {
                node = fields[i];
                break;
            }
        }
        if(node && node.value != "默认") {
            return node.value;
        }
    }

};